<template>
  <div class="chart-container" style="height: 300px">
    <div ref="chart" style="height: 100%"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'BarChart',
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    this.initChart()
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose()
      this.chart = null
    }
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$refs.chart)
      this.setOptions([])
    },
    setOptions(data = []) {
      const xAxisData = data.map(item => item.date)
      const leaveData = data.map(item => item.count)
      // 计算完成率，这里使用模拟数据，实际应该从后端获取
      const completionData = data.map(item => item.completion || Math.round(Math.random() * 30 + 60))
      
      this.chart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        legend: {
          data: ['请假数', '完成率']
        },
        xAxis: [
          {
            type: 'category',
            data: xAxisData,
            axisPointer: {
              type: 'shadow'
            },
            axisTick: {
              alignWithLabel: true
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '请假数',
            position: 'left',
            axisLine: {
              show: true,
              lineStyle: {
                color: '#5470C6'
              }
            },
            axisLabel: {
              formatter: '{value}'
            }
          },
          {
            type: 'value',
            name: '完成率',
            position: 'right',
            axisLine: {
              show: true,
              lineStyle: {
                color: '#91CC75'
              }
            },
            axisLabel: {
              formatter: '{value}%'
            },
            splitLine: {
              show: false
            }
          }
        ],
        series: [
          {
            name: '请假数',
            type: 'bar',
            barWidth: '40%',
            data: leaveData,
            itemStyle: {
              color: '#5470C6'
            }
          },
          {
            name: '完成率',
            type: 'line',
            yAxisIndex: 1,
            smooth: true,
            data: completionData,
            itemStyle: {
              color: '#91CC75'
            },
            lineStyle: {
              width: 3
            },
            symbolSize: 8
          }
        ]
      })
    },
    updateChart(data) {
      this.setOptions(data)
    }
  }
}
</script>

<style scoped>
.chart-container {
  position: relative;
  padding: 20px;
  background: #fff;
}
</style>
  